<template>
  <div>
    <!-- 自定义导航 -->
    <van-nav-bar :title="navName" left-text="" right-text="编辑" left-arrow @click-left="Returns" @click-right="edit" v-if="navShowPerv" :fixed="true"/>
    <van-nav-bar :title="navName" left-text="取消" right-text="保存" left-arrow @click-left="cancel" @click-right="save" v-if="navShowEdit" :fixed="true"/>
    <van-cell-group style="padding-top:51px" @click="Wrning">
      <van-field v-model="from.code" label="设备编号" placeholder="请输入" required  right-icon="scan" size="large" :disabled="allow" @click-right-icon="goscan" :error="checkVal.codeErr" @focus="checkVal.codeErr=false" input-align="right"/>
      <van-field v-model="from.name" label="设备名称" placeholder="请输入" required :disabled="allow" :error="checkVal.nameErr" @focus="checkVal.nameErr=false" size="large" clearable input-align="right"/>

      <van-cell title="请选择设备系统" is-link size="large" :value="from.systems" @click="systemIdshow=tancen" required clearable/>
      <!-- 设备系统 弹层 -->
      <van-action-sheet v-model="systemIdshow" :actions="systemVal" @select="systemSelect"/>

      <van-cell title="请选择设备类别" size="large" is-link :value="from.specClass" @click="specClassshow=tancen" requireds required/>
      <!-- 设备类别 弹层 -->
      <van-action-sheet v-model="specClassshow" :actions="specClassVal" @select="specClasss"/>

     <van-field label="设备使用时间" label-width="200px" v-model="from.startDate" placeholder="请选择" input-align="right" clearable right-icon="arrow" disabled @click="startDateShow=tancen" required />
      <!-- 时间日期弹窗 -->
      <div>
        <van-popup v-model="startDateShow" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @cancel="arrivetime = false" @confirm="startDateConfirm" />
        </van-popup>
      </div>
    </van-cell-group>
    <van-field type="number" v-model="from.quantity" label="数量" placeholder="请输入" required :disabled="allow" :error="checkVal.quantityErr" @focus="checkVal.quantityErr=false" clearable input-align="right"/>
    <!-- <van-cell-group>
      <van-switch-cell v-model="from.isemploy" :class="openstyles" title="设备是否使用" @change="changecolor" :disabled="allow" active-value="1" inactive-value="0"/>
    </van-cell-group> -->
    <!-- <van-cell-group>
      <van-switch-cell v-model="from.inspect" :class="openstyles" title="设备是否需要进行巡检" @change="changecolor" :disabled="allow" active-value="1" inactive-value="0"/>
    </van-cell-group>
     -->
    <van-cell-group>
      <van-switch-cell v-model="from.status" :class="openstyles" title="是否启用该设备"  @change="changecolor" active-value="1" inactive-value="2" :disabled="allow" active-color="#13ce66"/>
    </van-cell-group>
    <van-field type="textarea" v-model="from.description" size="large" label="设备描述" placeholder="请输入" :disabled="allow" clearable :maxlength="140" show-word-limit autosize/>
  </div>
</template>
<script>
export default {
  data(){
    return{
      isStatus: true, //是否启用 
      startDateShow: false,
      currentDate: new Date(), //设备使用时间
      //错误检查
      checkVal:{
        codeErr: false,
        nameErr: false,
        startDate: false,
        quantityErr: false,
      },  
      tancen:false,
      allow:true, //是否允许编辑
      navShowPerv: true, 
      navShowEdit: false, 
      navName: localStorage.getItem('navName'), //导航名称
      systemIdshow: false,  //设备类别 弹层变量
      specClassshow:false,  //设备类别 弹层
      //设备系统
      systemVal: [
        // { id: '1', subname: 'AAA系统', classfication:'122' },
      ],
      //设备类别
      specClassVal: [
        // { id: '1', subname: '家电类', classfication:'122' },
      ],
      
      openstyles:'', 
      from:{
        code:'',       //设备编号
        name:'',          //设备名称
        systemId: '',          //设备系统ID
        systems: '',          //设备系统名称
        specClassId:'',       //设备类别ID
        specClass:'',         //设备类别名称
        description:'',       //设备描述信息
          isemploy:'0',           //设备是否使用
        startDate:'',         //设备使用时间
          inspect:'0',          //设备是否需要进行巡检
        quantity:'',          //数量
        status:'2'            //是否启用该设备
      },
    }
  },
  methods:{
    
    startDateConfirm(value){
      this.from.startDate = this.$moment(value).format("YYYY-MM-DD");
      this.startDateShow = false;
    },
    //预览状态是提示
    Wrning(){
      if(this.allow==true){
        this.$toast.fail("预览状态下不可编辑！");
        return;
      }
    },
    // 设备是扫码
    goscan(){
      //钉钉扫码
      if(this.allow==true){
        return;
      }else{
        let that = this;
        this.$dd.biz.util.scan({
          type: String , // type 为 all、qrCode、barCode，默认是all。
          onSuccess: function(data) {
          //onSuccess将在扫码成功之后回调
          /* data结构
            { 'text': String}
          */
          that.from.code = data.text;
          },
          onFail : function(err) {
          }
        })
      }
      
    },
    //选择设备系统
    systemSelect(item) {
      // 点击选项时默认不会关闭菜单，可以手动关闭
      this.systemIdshow = false;
      this.from.systems = item.subname;  //选中的设备类别名（赋值）
      this.from.systemId = item.id;
      this.getspecClassData(item.id)
    },
    //选择设备类别
    specClasss(item) {
      // 点击选项时默认不会关闭菜单，可以手动关闭
      this.specClassshow = false;
      this.from.specClass = item.subname;  //选中的设备类别名（赋值）
      this.from.specClassId = item.id;
    },
    //设备系统数据 获取
    getsystemData(){
      this.$http.get(`/api/constants/getConstantsList?classfication=system&status=1`, {
          headers:{ 'Authorization':localStorage.getItem('token'),}
        }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.length == 0){
            this.systemIdshow = false;
            this.$toast.fail("设备系统数据为空");
          }
          this.systemVal = []; //清空
           for (let index = 0; index < res.data.data.length; index++) {
            this.systemVal.push(
              {id: res.data.data[index].id,
               subname: res.data.data[index].name,
               classfication: res.data.data[index].classfication 
            });
             
           }
        }
       
      })
    },
    //设备类别 获取
    getspecClassData(val){
      this.$http.get(`/api/specs/getSpecsList?limit=99&page=0&systemId=${val}`, {
          headers:{ 'Authorization':localStorage.getItem('token'),}
        }).then(res =>{
        if(res.data.errcode == 0){
           if(res.data.data.list == 0){
            this.specClassshow = false;
            this.$toast.fail("设备类别为空");
          }
          this.specClassVal = []; //置空
           for (let index = 0; index < res.data.data.list.length; index++) {
            this.specClassVal.push(
              {id: res.data.data.list[index].specclassid,
               subname: res.data.data.list[index].specclass,
              //  classfication: res.data.data[index].classfication 
            });
           }
        }
       
      })
    },
    //返回上一层
    Returns(){
      this.$router.go(-1);
    },
    //取消编辑
    cancel() {
    this.$dialog.confirm({
      title: '提示', message: '是否放弃本次编辑？'
      }).then(() => {
        this.$router.push({path: '/equipment'});
      }).catch(() => {});
    },
    //编辑
    edit() {
      //this.getIsStatus()//编辑查询父级空间是否启用
      this.navShowPerv = false; //预览隐藏
      this.navShowEdit = true;  //编辑显示
      this.allow = false; //允许编辑\
      this.tancen = true; //允许弹层可点
    },
    //保存
    save(){
      
      if(!this.from.code){
        this.checkVal.codeErr = true;
        return this.$toast("设备编号不能为空！");
      }
      if(!this.from.name){
        this.checkVal.nameErr = true;
        return this.$toast("设备名称不能为空！");
      }
      if(!this.from.startDate){
        this.checkVal.startDateErr = true;
        return this.$toast("设备使用时间称不能为空！");
      }
      if(!this.from.quantity){
        this.checkVal.quantityErr = true;
        return this.$toast("数量不能为空！");
      }
      let ProID = sessionStorage.getItem("ProID");
      let buildID = sessionStorage.getItem("buildID");
      let floorID = sessionStorage.getItem("floorID");
      let spacesID = sessionStorage.getItem("spacesID");
      let equiomentID = sessionStorage.getItem("equiomentID");
      let data = {
        id: equiomentID,
        locationId: ProID,
        buildingId: buildID,
        floorId: floorID,
        spaceId: spacesID,
        code: this.from.code,
        name: this.from.name,
        systemId: this.from.systemId,
        systems: this.from.systems,
        specClassId: this.from.specClassId,
        specClass: this.from.specClass,
        description: this.from.description,
        isemploy: parseInt(this.from.isemploy),
        startDate: this.from.startDate,
        inspect: parseInt(this.from.inspect),
        quantity: this.from.quantity,
        status: parseInt(this.from.status),
      }
      this.$http.put(`/api/equipments/modifyEquipments`, data).then(res =>{
        if(res.data.errcode == -3){
          this.nameErr = true;
          this.$toast.fail("编辑失败，设备名重复");
          return;
        }
        if(res.data.errcode == 0){
          this.from = {};
          this.$toast('设备编辑成功!');
          this.$router.replace({path: '/equipment'})
        }else{
          this.$toast('设备编辑失败!');
        }
      })
    },
    // 开关改变颜色
    changecolor(){
      if(this.from.isMaintained === true){
        this.openstyles='open';
      }else{
        this.openstyles='';
      }
    },
    //判断父级空间是否启用 父级未启用 子级不可启用
    getIsStatus(){
      let spacesID = sessionStorage.getItem('spacesID');
      this.$http({
        url: "/api/spaces/getSpacesById",
        method: "get",
        params: {
          id: spacesID,
        },
        headers:{Authorization: localStorage.getItem("token")}
      }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.status==2){
            this.from.status = 2;
            this.isStatus = true;
          }
        }
      }).catch(err =>{
        console.log({err});
      })
    }
  },
  created(){
    // this.getIsStatus(); //判断父级空间是否启用 父级未启用 子级不可
    this.getsystemData();
    let val = JSON.parse(sessionStorage.getItem("equiomentVal"));
    this.from = val;
    let t = this.$moment(val.startDate).format("YYYY-DD-MM")
    this.from = {
      code: val.code,              //设备编号
      name: val.name,                //设备名称
      systemId: val.systemId,        //设备系统ID
      systems: val.systems,             //设备系统名称
      specClassId: val.specClassId,    //设备类别ID
      specClass: val.specClass,         //设备类别名称
      description: val.description,       //设备描述信息
      isemploy: (val.isEmploy).toString(),    //设备是否使用(未提供)
      startDate: t,      //设备使用时间
      inspect: (val.inspect).toString(),  //设备是否需要进行巡检(未提供)
      quantity: val.quantity,          //数量
      status: (val.status).toString(),          //是否启用该设备
    }
    if(this.$route.query.isEdit=='edit'){
      this.edit();
    }
  }
}

</script>

<style scoped>
  .van-cell {
    color: #979797 !important;
  }
  /* 开关选择颜色 */
  .open{
    color: #333 !important;
  }
.van-icon-scan:before {
  content: "\F0AD";
  font-size: 35px !important;
}
.van-field__control{
  color:#333 !important;
}
.van-field__control:disabled{
  color:#333 !important;
}
.van-field--disabled .van-field__control, .van-field__right-icon{
  color: red;
}
</style>